var mysql = require('mysql');
var mongoose = require('mongoose');

var constants = require('../constants.js');

/*
 * MySQL connection configuration
 */
var connection = mysql.createConnection({
  host     : constants.db.HOST,
  user     : constants.db.USER,
  password : constants.db.PASSWORD,
  insecureAuth: true
});

connection.connect();
connection.query('USE ' + constants.db.DATABASE);

/*
 * Export functions
 */
exports.login = function(username, password, handler) {
	connection.query('SELECT * FROM ttmembers WHERE user = ? and pass = ?', [username, password], function(err, rows, fields) {
		var result = false;
		if (rows.length > 0) {
			result = true;
		}
		
		handler(result);
	});
};

// Buddy operation
exports.getBuddies = function(username, handler) {
	connection.query('SELECT friend, unread FROM ttfriends WHERE user = ?', [username], function(err, rows, fields) {
		handler(rows);
	});
};

// Unread operation
exports.getUnread = function(username, friend, handler) {
	connection.query('SELECT unread FROM ttfriends WHERE user = ? and friend = ?', [username, friend], function(err, rows, fields) {
		handler(rows);
	});
};

exports.setUnread = function(username, friend, unread) {
	connection.query('UPDATE ttfriends SET unread = ? WHERE user = ? and friend = ?', [unread, username, friend]);
};

exports.increaseUnread = function(username, friend) {
	connection.query('UPDATE ttfriends SET unread = unread + 1 WHERE user = ? and friend = ?', [username, friend]);
};

exports.decreaseUnread = function(username, friend) {
	connection.query('UPDATE ttfriends SET unread = unread - 1 WHERE user = ? and friend = ?', [username, friend]);
};